package org.microservice.auth.entity;

import org.apache.commons.lang.StringUtils;
import org.microservice.common.bean.MenuVo;
import org.microservice.common.bean.UserVo;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author lengleng
 * @date 2017/10/29
 */

public class UserDetailsImpl implements UserDetails {
    private static final long serialVersionUID = 1L;

    private String username;
    private String password;
    private int id;
    private boolean disabled;
    private List<MenuVo> menus = new ArrayList<>();

    public UserDetailsImpl(UserVo userVo, List<MenuVo> menus) {
        this.username = userVo.getUsername(); //+"#"+userVo.getId()
        this.password = userVo.getPassword();
        this.disabled = userVo.isDisabled();
        this.id = userVo.getId();

        this.menus = menus;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> authorityList = new ArrayList<>();
        if(menus != null){
            for (MenuVo menu : menus) {
                if(StringUtils.isNotEmpty(menu.getPerms())){
                    authorityList.add(new SimpleGrantedAuthority(menu.getPerms()));
                }
            }
        }

        return authorityList;
    }

    @Override
    public String getPassword() {
        return this.password;
    }

    @Override
    public String getUsername() {
        return this.username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return this.disabled;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
}
